#include "dialog_compass.h"
#include "ui_dialog_compass.h"
#define GET_ARRAY_LEN(array,len){len = (sizeof(array) / sizeof(array[0]));}

// 接收地址
const char *hostArr[] = {"120100","100010"};
// 报警编号
const char *codeboxArr[] = {"61","62","71","81","91"};

// 北斗发送
Dialog_Compass::Dialog_Compass(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Dialog_Compass)
{
    ui->setupUi(this);
    SERIALPORTCONFIG_INSTANCE->getSerialPortInfo(m_vecSerialInfo);

    // 北斗编号
    QStringList hostList;
    int hostLen;
    GET_ARRAY_LEN(hostArr,hostLen);
    for(int i=0;i<hostLen;i++){
        hostList<<hostArr[i];
    }
    ui->compassHostBox->addItems(hostList);

    // 报警编号
    QStringList codeList;
    int len;
    GET_ARRAY_LEN(codeboxArr,len);
    for(int i=0;i<len;i++){
        codeList<<codeboxArr[i];
    }
    ui->compassCodeBox->addItems(codeList);

    // 关闭信号槽
    connect(ui->closeButton,SIGNAL(clicked()),this,SLOT(close()));

}

Dialog_Compass::~Dialog_Compass()
{
    delete ui;
}

// 发送数据
void Dialog_Compass::on_compassSendBtn_clicked()
{
    // 主机地址
    QString hostEdit = ui->compassHostBox->currentText();
    // 报文编号
    QString codeBoxEdit = ui->compassCodeBox->currentText();
    // 报文内容
    QString sendEdit = ui->compassSendEdit->toPlainText();

    if(sendEdit == ""){
        QMessageBox::warning(NULL, "提示", QStringLiteral("报文内容不能为空"));
        return;
    }

    // 获取系统参数
    PSysparamInfo info;
    SERIALPORTCONFIG_INSTANCE->getSysParamInfo(info);

    // 获取当前时间
    QDateTime time = QDateTime::currentDateTime();
    QString mesc = SERIALPORTCONFIG_INSTANCE->getMilliseconds(time);
    QString strRecv = QString("%1%2 %3 %4 %5%6").arg("\"").arg(codeBoxEdit)
            .arg(mesc).arg(sendEdit).arg(info.cplate).arg("\"");

    strName = m_vecSerialInfo[3].name;
    if(!SERIALPORTCTRL_INSTANCE->isOpened(strName)){
        SERIALPORTCTRL_INSTANCE->open_port(strName);
    }

    // 发送指令
    QString cmd;
    cmd = QString("AT+SEND=%1,%2%3\r\n").arg(hostEdit).arg(strRecv).arg("^Z");

    SERIALPORTCTRL_INSTANCE->write_data(strName, cmd, false);

    QMessageBox::information(NULL, "提示", QStringLiteral("报文发送成功"));
}

// 报文内容限制长度
void Dialog_Compass::on_compassSendEdit_textChanged()
{
    QString textContent = ui->compassSendEdit->toPlainText();
    int length = textContent.count();
    int maxLength = 30; // 最大字符数
    if(length > maxLength)
    {
        int position = ui->compassSendEdit->textCursor().position();
        QTextCursor textCursor = ui->compassSendEdit->textCursor();
        textContent.remove(position - (length - maxLength), length - maxLength);
        ui->compassSendEdit->setText(textContent);
        textCursor.setPosition(position - (length - maxLength));
        ui->compassSendEdit->setTextCursor(textCursor);
        length = maxLength;
    }
}
